package com.yonyougov.devops.cruxcisupport.k8s.configmap;

import com.yonyougov.devops.cruxcisupport.k8s.K8sRepository;
import com.yonyougov.devops.cruxcisupport.k8s.error.K8sConfIgNotFindException;
import io.fabric8.kubernetes.api.model.ConfigMap;
import io.fabric8.kubernetes.api.model.ConfigMapBuilder;
import io.fabric8.kubernetes.client.KubernetesClient;
import lombok.SneakyThrows;
import org.springframework.stereotype.Repository;

@Repository
public class ConfigMapRepositoryImpl implements ConfigMapRepository{
    private final K8sRepository k8sRepository;

    public ConfigMapRepositoryImpl(K8sRepository k8sRepository) {
        this.k8sRepository = k8sRepository;
    }

    @Override
    public ConfigMap createOrReplace(ConfigMapRequest request) throws K8sConfIgNotFindException, InterruptedException {
        KubernetesClient client = k8sRepository.createDefaultClient(request.getNameSpace());
        ConfigMap result = null;
        try{
            ConfigMap configMap = new ConfigMapBuilder().
                    withNewMetadata().withName(request.getName()).endMetadata().
                    addToData(request.getDatas()).
                    build();
            ConfigMap oldConfigMap = client.configMaps().inNamespace(request.getNameSpace()).withName(request.getName()).get();
            if(null != oldConfigMap){
                client.configMaps().inNamespace(request.getNameSpace()).withName(request.getName()).delete();
            }
            Thread.sleep(1000);
            result = client.configMaps().inNamespace(request.getNameSpace()).create(configMap);
        }finally {
            client.close();
        }
        return result;
    }

    @Override
    public ConfigMap get(String name,String nameSpace) throws K8sConfIgNotFindException {
        KubernetesClient client = k8sRepository.createDefaultClient(nameSpace);
        ConfigMap configMap = null;
        try{
            configMap = client.configMaps().inNamespace(nameSpace).withName(name).get();
        }finally {
            client.close();
        }
        return configMap;
    }
}
